import { Component, OnInit } from "@angular/core";
import { AppRate } from "@ionic-native/app-rate/ngx";
import { AppVersion } from "@ionic-native/app-version/ngx";
import { InAppPurchase } from "@ionic-native/in-app-purchase/ngx";
import { Market } from "@ionic-native/market/ngx";
import { LoadingController, ModalController, ToastController } from "@ionic/angular";
import { ChooseLanguagePage } from "./../choose-language/choose-language.page";
import { EventsService } from "./../events.service";
import { Global } from "./../global.service";
import { LocalStorage } from "./../local-storage.service";

@Component({
	selector: "app-settings",
	templateUrl: "./settings.page.html",
	styleUrls: ["./settings.page.scss"],
})
export class SettingsPage implements OnInit {
	version = "";
	productions = [];

	constructor(
		private modalCtrl: ModalController,
		private toastCtrl: ToastController,
		private appRate: AppRate,
		private appVersion: AppVersion,
		private market: Market,
		private iap: InAppPurchase,
		private localStorage: LocalStorage,
		private events: EventsService,
		private loadingCtrl: LoadingController,
		private global: Global
	) { }

	ngOnInit() {
		this.appVersion.getVersionNumber().then(
			version => { this.version = version; }
		);
		this.iap.getProducts([Global.IAP]).then(response => {
			this.productions = response;
		});
		this.appRate.setPreferences({
			storeAppURL: {
				ios: Global.APP_ID
			}
		});
	}

	rate() {
		this.appRate.navigateToAppStore();
	}

	buy() {
		this.iap.buy(Global.IAP)
			.then((data) => {
				this.toast(this.translate("PRASE_VIP_SUCCESS"));
				this.localStorage.setData(Global.IAP, data);
				this.events.broadcast(Global.IAP);
			}, () => {
				this.toast(this.translate("PRASE_VIP_FAILED"));
			});
	}

	restore() {
		this.iap.restorePurchases().then(
			response => {
				for (const product of response) {
					if (product.productId === Global.IAP) {
						this.localStorage.setData(Global.IAP, product);
						this.events.broadcast(Global.IAP);
						this.toast(this.translate("RESTORE_VIP_SUCCESS"));
						return;
					}
				}

				this.toast(this.translate("RESTORE_VIP_FAILED"));
			}
		);
	}

	get showIPA(): boolean {
		return !this.localStorage.getData(Global.IAP);
	}

	async checkUpdate() {
		const loading = await this.loadingCtrl.create();
		await loading.present();
		this.market.open(Global.APP_ID).then().finally(() => {
			loading.dismiss();
		});
	}

	async dismiss() {
		await this.modalCtrl.dismiss();
	}

	async chooseLanguage() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: ChooseLanguagePage
		});

		await modal.present();
	}

	private async toast(message: string) {
		const toast = await this.toastCtrl.create({
			message,
			duration: 3000
		});
		await toast.present();
	}


	translate(key: string) {
		return this.global.translate(key);
	}
}
